package com.project.forlearningdemo.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.project.forlearningdemo.constant.ResponseTool;
import com.project.forlearningdemo.dao.UserMapper;
import com.project.forlearningdemo.pojo.User;
import com.project.forlearningdemo.pojo.vo.ResponseInfo;
import com.project.forlearningdemo.service.RedisService;
import com.project.forlearningdemo.service.UserService;
import com.project.forlearningdemo.utils.StringUtils;
import com.project.forlearningdemo.utils.TokenUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;
    @Autowired
    JavaMailSender javaMailSender;
    @Autowired
    RedisService redisService;

    /**
     * 查找用户
     */
    @Override
    public String findUser(String user) {
        JSONObject jsonObject = JSONObject.parseObject(user);
        String username = jsonObject.getString("username");
        Integer userId = jsonObject.getInteger("userId");
        String mail = jsonObject.getString("mail");
        System.out.println("hhhh");
        if(username == null && userId == null && mail == null) return JSON.toJSONString(new ResponseInfo<>(500, "至少有一个参数不为空", false));
        User user1 = userMapper.queryUser(userId, username, mail);
        if(user1==null)
            return JSON.toJSONString(new ResponseInfo<>(ResponseTool.QUERY_FAIL.code, ResponseTool.QUERY_FAIL.msg, false));
        return JSON.toJSONString(new ResponseInfo<>(ResponseTool.QUERY_SUCCESS.code, ResponseTool.QUERY_SUCCESS.msg, user1));
    }

    /**
     *  更改用户
     */
    @Override
    public String updateUser(String user) {
        User user1 = (User)StringUtils.tranJSON(user, new User());
        userMapper.updateUser(user1);
        return JSON.toJSONString(new ResponseInfo<>(ResponseTool.UPDATE_SUCCESS.code, ResponseTool.UPDATE_SUCCESS.msg, true));
    }

    /**
     * 增加用户
     */
    public String addUser(String user){
        User user1 = (User)StringUtils.tranJSON(user, new User());
        if(userMapper.insertUser(user1))
            return JSON.toJSONString(new ResponseInfo<>(ResponseTool.ADD_SUCCESS.code, ResponseTool.ADD_SUCCESS.msg, true));
        return JSON.toJSONString(new ResponseInfo<>(ResponseTool.ADD_FAIL.code, ResponseTool.ADD_FAIL.msg, false));
    }

    /**
     *  删除用户
     */
    @Override
    public String deleteUser(Integer userId) {
        if(userMapper.deleteUser(userId)){
            return JSON.toJSONString(new ResponseInfo<>(ResponseTool.DELETE_SUCCESS.code, ResponseTool.DELETE_SUCCESS.msg, true));
        }
        return JSON.toJSONString(new ResponseInfo<>(ResponseTool.DELETE_FAIL.code, ResponseTool.DELETE_FAIL.msg, true));
    }

    /**
     *  用户注册
     */
    @Override
    public synchronized String registerUser(String mpc) throws MessagingException {

        JSONObject jsonObject = JSONObject.parseObject(mpc);
        String mail = (String) jsonObject.get("mail");
        String pass = (String) jsonObject.get("password");
        String code = (String) jsonObject.get("code");

        //邮箱或密码不能为空或空串
        if(StringUtils.isEmpty(mail, pass, code))
            return JSON.toJSONString(new ResponseInfo<>(504, "邮箱或密码不能为空或空串", false));

        //校验验证码
        String code1 = (String) redisService.get("code");
        if (code1 == null) return JSON.toJSONString(new ResponseInfo<>(500, "验证码失效", false));
        if (!code1.equals(code)) {
            redisService.del("code");
            return  JSON.toJSONString(new ResponseInfo<>(500, "验证码错误", false));
        }

        //是否存在邮箱号
        if(userMapper.queryUser(null, null, mail) != null)
            return JSON.toJSONString(new ResponseInfo<>(505, "存在重复邮箱号", false));

        //生成账号
        String username = StringUtils.createName();

        //加密
        String password = StringUtils.tranPass(pass);

        //发送邮箱
        this.sendMail(username, mail);

        //注册
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setMail(mail);

        if(userMapper.insertUser(user)){
            return JSON.toJSONString(new ResponseInfo<>(200,"注册成功", true));
        }

        return JSON.toJSONString(new ResponseInfo<>(505, "注册失败，数据库添加信息错误", false));
    }

    /**
     *  用户登录
     */
    @Override
    public String loginUser(String up, HttpServletRequest request) {
        JSONObject jsonObject = JSONObject.parseObject(up);
        String username = jsonObject.getString("username");
        String pass = jsonObject.getString("password");

        //邮箱或密码不能为空或空串
        if(StringUtils.isEmpty(username, pass))
            return JSON.toJSONString(new ResponseInfo<>(505, "账号或密码不能为空或空串", false));

        Subject subject = SecurityUtils.getSubject();
        subject.login(new UsernamePasswordToken(username, StringUtils.tranPass(pass)));

        Map<String, Object> map = new HashMap<>();
        User user = (User) subject.getPrincipal();
        map.put("user", user);
        map.put("token", TokenUtil.getToken(String.valueOf(user.getUserId()), user.getUsername(), request.getRemoteAddr()));

        return JSON.toJSONString(new ResponseInfo<>(200, "登录成功", map));
    }


    /**
     * 忘记密码
     */
    @Override
    public synchronized String updateUserPass(String mpc) {
        JSONObject jsonObject = JSONObject.parseObject(mpc);
        String mail = jsonObject.getString("mail");
        String pass = jsonObject.getString("password");
        String code = jsonObject.getString("code");

        //邮箱或密码不能为空或空串
        if(StringUtils.isEmpty(mail, pass, code))
            return JSON.toJSONString(new ResponseInfo<>(505, "邮箱或密码不能为空或空串", false));

        //校验验证码
        String code1 = (String) redisService.get("code");
        if (code1 == null) return JSON.toJSONString(new ResponseInfo<>(500, "验证码失效", false));
        if (!code1.equals(code)) {
            redisService.del("code");
            return JSON.toJSONString(new ResponseInfo<>(500, "验证码错误", false));
        }

        //判断邮箱号是否存在
        User user = userMapper.queryUser(null, null, mail);
        if(user == null)
            return JSON.toJSONString(new ResponseInfo<>(404, "不存在邮箱号", false));

        //加密
        String newPass = StringUtils.tranPass(pass);

        //封装新对象
        User newUser = new User();
        newUser.setMail(mail);
        newUser.setPassword(newPass);

        //更改密码
        user.setPassword(newPass);

        //更改数据库中的密码
        if(userMapper.updateUser(newUser))
            return JSON.toJSONString(new ResponseInfo<>(ResponseTool.UPDATE_SUCCESS.code, ResponseTool.UPDATE_SUCCESS.msg, user));

        return JSON.toJSONString(new ResponseInfo<>(ResponseTool.UPDATE_FAIL.code, ResponseTool.UPDATE_FAIL.msg, false));
    }

    /**
     * 发送验证码
     */
    public String sendCode(String mail1) throws MessagingException {
        //转化
        JSONObject jsonObject = JSONObject.parseObject(mail1);
        String mail = jsonObject.getString("mail");

        if(StringUtils.isEmpty(mail))
            return JSON.toJSONString(new ResponseInfo<>(405, "邮箱号不能为空", false)) ;

        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, false);
        helper.setSubject("For learning | 通知");
        String code = StringUtils.createCode();
        redisService.set("code", code, 180);
        helper.setText("<p>你好，您的验证码为：" + code +"，3分钟内有效，请您尽快验证！</p>", true);
        helper.setFrom("1804859224@qq.com");
        helper.setTo(mail);
        javaMailSender.send(message);

        return JSON.toJSONString(new ResponseInfo<>(200, "验证码发送成功", true));
    }

    /**
     * 发送邮箱
     */
    private void sendMail(String adminName, String mail) throws MessagingException {

        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, false);
        helper.setSubject("For learning | 用户账号信息通知");
        helper.setText("<p>你好，您的账号为：</p><p>"+adminName+"</p><p>请记住您的用户账号</p>", true);
        helper.setFrom("1804859224@qq.com");
        helper.setTo(mail);
        javaMailSender.send(message);
    }

    /**
     * 注销
     */
    @Override
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return JSON.toJSONString(new ResponseInfo<>(200, "成功注销!", true));
    }

}
